<template>
  <!-- 预定仓位 -->
  <customContainer ref="mainRef" :config="config" />
  <div>
    <!-- 新增、修改 -->
    <el-dialog
      v-model="open"
      :title="title"
      width="500px"
      class="mydialog"
      :before-close="cancel"
    >
      <el-form
        ref="dialogForms"
        :model="dialogForm"
        :rules="rules"
        label-width="110px"
      >
        <el-form-item label="销售产品" prop="sealProduct">
          <el-select
            v-model="dialogForm.sealProduct"
            filterable
            style="width: 200px;"
            placeholder="请输入销售产品"
            clearable
          >
            <el-option
              v-for="dict in dicts[DictDirection.产品]"
              :key="dict.salesProductCode"
              :label="dict.salesProductName"
              :value="dict.salesProductCode"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="预定开始日期" prop="scheduledStartTime" sortable>
          <el-date-picker
            v-model="dialogForm.scheduledStartTime"
            type="date"
            value-format="YYYY-MM-DD"
            placeholder="选择日期"
          ></el-date-picker>
        </el-form-item>
        <el-form-item label="预定截止日期" prop="scheduledEndTime" sortable>
          <el-date-picker
            v-model="dialogForm.scheduledEndTime"
            type="date"
            value-format="YYYY-MM-DD"
            placeholder="选择日期"
          ></el-date-picker>
        </el-form-item>
        <el-form-item label="开船日" prop="receivingTime" sortable>
          <el-date-picker
            v-model="dialogForm.receivingTime"
            type="date"
            value-format="YYYY-MM-DD"
            placeholder="选择日期"
          ></el-date-picker>
        </el-form-item>
      </el-form>
      <div>
        <el-button type="primary" @click="submitForm">确定</el-button>
        <el-button type="info" @click="cancel">取消</el-button>
      </div>
    </el-dialog>
    <!-- 订舱详情 -->
    <el-dialog
      v-model="orderDetail"
      :title="orderDetailTitle"
      width="50%"
      class="mydialog"
    >
      <el-row :gutter="10" class="mb8">
        <el-col :span="1.5">
          <el-button type="primary" :icon="Plus" @click="handleAddOrderDetail">新增</el-button>
        </el-col>
      </el-row>
      <el-table v-loading="xqloading" border :data="orderDetailTable">
        <el-table-column type="selection" align="center" width="55"></el-table-column>
        <el-table-column
          label="区域名称"
          min-width="100"
          show-overflow-tooltip
          prop="deptId"
          align="center"
          :formatter="(row) => dicts.getDictLabel({ dict: DictDirection.大区, value: row.deptId })"
        ></el-table-column>
        <el-table-column label="总方数" prop="totalPower" align="center"></el-table-column>
        <el-table-column
          label="可预订方数"
          min-width="100"
          prop="orderDeterminedPower"
          align="center"
        ></el-table-column>
        <el-table-column label="已定方数" prop="determinedPower" align="center"></el-table-column>
        <el-table-column label="操作" align="center" width="200">
          <template #default="{ row }">
            <el-button type="primary" text @click="editAddOrderDetail(row)">修改</el-button>
            <el-button type="primary" text @click="delAddOrderDetail(row)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>
    </el-dialog>
    <!-- 订舱详情——新增、修改 -->
    <el-dialog
      v-model="openAddOrderDetail"
      :title="addOrderDetailTitle"
      width="500px"
      class="mydialog"
    >
      <el-form
        ref="addOrderDetails"
        :model="addOrderDetail"
        :rules="rules"
        label-width="110px"
      >
        <el-form-item v-if="addOrderDetailTitle === '新增'" label="区域名称" prop="deptId">
          <el-select v-model="addOrderDetail.deptId" placeholder="请输入区域名称" clearable>
            <el-option
              v-for="dict in dicts[DictDirection.大区]"
              :key="dict.deptId"
              :label="dict.deptName"
              :value="dict.deptId"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item v-else label="区域名称" prop="deptName">
          <el-select v-model="addOrderDetail.deptName" placeholder="请输入区域名称" clearable>
            <el-option
              v-for="dict in dicts[DictDirection.大区]"
              :key="dict.deptId"
              :label="dict.deptName"
              :value="dict.deptId"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="总方数" prop="totalPower">
          <el-input
            v-model="addOrderDetail.totalPower"
            placeholder="请输入总方数"
            clearable
          />
        </el-form-item>
        <el-form-item label="可预定方数" prop="orderDeterminedPower">
          <el-input
            v-model="addOrderDetail.orderDeterminedPower"
            placeholder="请输入可定方数"
            clearable
          />
        </el-form-item>
        <el-form-item label="订舱日期" prop="time">
          <el-date-picker
            v-model="addOrderDetail.time"
            type="date"
            value-format="YYYY-MM-DD"
            placeholder="选择日期"
          ></el-date-picker>
        </el-form-item>
      </el-form>
      <div>
        <el-button type="primary" @click="submitAddOrderDetail">确定</el-button>
        <el-button type="info" @click="cancelAddOrderDetail">取消</el-button>
      </div>
    </el-dialog>
    <!-- 预定详情 -->
    <el-dialog
      v-model="openDetail"
      :title="titleDetail"
      width="1000px"
      class="mydialog"
      :before-close="cancle2"
    >
      <el-form
        ref="orderDetailForms"
        inline
        :model="orderDetailForm"
        label-width="80px"
      >
        <el-form-item label="区域名称" props="deptId">
          <el-select
            v-model="orderDetailForm.deptId"
            placeholder="请输入区域名称"
            clearable
          >
            <el-option
              v-for="dict in dicts[DictDirection.大区]"
              :key="dict.deptId"
              :label="dict.deptName"
              :value="dict.deptId"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="客户名称" prop="customerCode">
          <el-select
            v-model="orderDetailForm.customerCode"
            style="width: 200px;"
            filterable
            placeholder="请选择客户"
            clearable
          >
            <el-option
              v-for="dict in dicts[DictDirection.客户]"
              :key="dict.customerCode"
              :label="dict.customerName"
              :value="dict.customerCode"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="状态" prop="status">
          <el-select v-model="orderDetailForm.status" clearable>
            <el-option
              v-for="dict in dicts[DictDirection.预定状态]"
              :key="dict.dictValue"
              :label="dict.dictLabel"
              :value="dict.dictValue"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="handleDetail({id:mids})">搜索</el-button>
          <el-button type="info" @click="resetOrderDetail({id:mids})">重置</el-button>
        </el-form-item>
      </el-form>
      <el-row :gutter="10" class="mb8">
        <el-col :span="1.5">
          <el-button type="warning" :icon="Download" @click="handleExport">导出</el-button>
        </el-col>
      </el-row>
      <el-table
        v-loading="tb3Loading"
        max-height="600px"
        style="width: 100%;"
        border
        :data="detailTable"
      >
        <el-table-column type="selection" align="center" width="55"></el-table-column>
        <el-table-column
          label="区域名称"
          prop="deptId"
          align="center"
          :formatter="(row) => dicts.getDictLabel({ dict: DictDirection.大区, value: row.deptId })"
        ></el-table-column>
        <el-table-column
          label="客户名称"
          prop="customerCode"
          align="center"
          :formatter="(row) => dicts.getDictLabel({ dict: DictDirection.客户, value: row.customerCode })"
        ></el-table-column>
        <el-table-column label="预订方数" prop="determinedPower" align="center"></el-table-column>
        <el-table-column label="操作" align="center">
          <template #default="{ row }">
            <el-button type="primary" text @click="handleDelDetail(row)">详情</el-button>
            <el-button type="primary" text @click="handleDelDetails(row)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>
    </el-dialog>
    <!-- 详情-》详情 -->
    <el-dialog v-model="open4" :title="title4" :before-close="cancle4">
      <el-form
        ref="forms"
        :model="form4"
        inline
      >
        <el-form-item label="状态" prop="status">
          <el-select v-model="form4.status" clearable>
            <el-option
              v-for="dict in dicts[DictDirection.预定状态]"
              :key="dict.dictValue"
              :label="dict.dictLabel"
              :value="dict.dictValue"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="handleDelDetail({mid:mid4,customerCode:customerCode4,deptId:deptId4})">搜索</el-button>
        </el-form-item>
      </el-form>
      <el-row :gutter="10" class="mb8">
        <el-col :span="3">
          <el-button type="warning" :disabled="multiple2 || isCancelCabin" @click="handleCancelCabin">取消订舱</el-button>
        </el-col>
      </el-row>
      <el-table v-loading="loading4" :data="data4" @selection-change="handleSelect4">
        <el-table-column type="selection" width="55" align="center"></el-table-column>
        <el-table-column label="预定方数" prop="determinedPower" align="center"></el-table-column>
        <el-table-column
          label="预定状态"
          prop="status"
          align="center"
          :formatter="(row) => dicts.getDictLabel({ dict: DictDirection.预定状态, value: row.status })"
        ></el-table-column>
        <el-table-column
          label="预定时间"
          show-overflow-tooltip
          prop="createDate"
          align="center"
        ></el-table-column>
        <el-table-column label="操作" align="center">
          <template #default="{ row }">
            <el-button
              type="primary"
              text
              :disabled="row.status == '2' || row.status == '-1' "
              @click="handleCancelCabin(row)"
            >
              取消预定
            </el-button>
            <el-button type="primary" text @click="handdel4(row)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>
    </el-dialog>
  </div>
</template>
<script lang="ts" setup>
import { ref, computed, getCurrentInstance, unref } from 'vue'
import { Plus, Download } from '@element-plus/icons-vue'
import { ElButton, ElMessageBox, ElMessage } from 'element-plus'
import useDicts, { DictDirection } from '@/store/modules/dicts'
// eslint-disable-next-line max-len
import { resevePositionManageList, insertSysResevePositionManage, updateSysResevePositionManage, deletePositionManageById, resevePositionManageDeailsList, delOrderDetail, getDetail, getDetail4, deleteCustomerBookingSpace, deleteDetails, cancelReserve, updateManageDeails, saveManageDeails } from '@/api/expressManager/bookingManage'

const dicts = useDicts()
dicts.setDicts(DictDirection.产品)
dicts.setDicts(DictDirection.大区)
dicts.setDicts(DictDirection.客户)
dicts.setDicts(DictDirection.预定状态)
const open = ref(false)
const open4 = ref(false)
const title = ref(null)
const title4 = ref(null)
const continueOpen = ref(true)
const multiple = ref(true)
const isCancelCabin = ref(true)
const mainRef = ref(undefined)
const xqloading = ref(false)
const tb3Loading = ref(false)
const openAddOrderDetail = ref(false)
const addOrderDetailTitle = ref(null)
const openDetail = ref(false)
const titleDetail = ref(null),
  {
    appContext: {
      config: {
        globalProperties: { $download, $validateForm },
      },
    },
  } = getCurrentInstance()
const mids = ref(null)
const orderDetailForm = ref({
  deptId: '',
  customerCode: '',
  status: '',
  mid: mids,
})

const orderDetailForms = ref(undefined)
const addOrderDetail = ref({
  deptId: '',
  deptName: '',
  totalPower: '',
  orderDeterminedPower: '',
  time: '',
  manageId: '',
})
const addOrderDetails = ref(undefined)
const dialogForm = ref({
  sealProduct: '',
  scheduledStartTime: '',
  scheduledEndTime: '',
  receivingTime: '',
})

const { proxy } = getCurrentInstance() as any
const dialogForms = ref()
const rules = {
  deptId: [{ required: true, message: '请输入大区部门ID', trigger: 'blur' }],
  deptName: [{ required: true, message: '请输入大区部门ID', trigger: 'blur' }],
  sealProduct: [{ required: true, message: '请输入销售产品', trigger: 'blur' }],
  sealProductName: [{ required: true, message: '请输入销售产品', trigger: 'blur' }],
  totalPower: [{ required: true, trigger: 'blur' }],
  orderDeterminedPower: [{ required: true, trigger: 'blur' }],
  totalAmount: [{ required: true, trigger: 'blur' }],
  scheduledStartTime: [{ required: true, message: '请输入预定开始日期', trigger: 'blur' }],
  receivingTime: [{ required: true, message: '请输入开船日', trigger: 'blur' }],
  scheduledEndTime: [{ required: true, trigger: 'blur' }],
}
const detailTable = ref([])
const orderDetail = ref(false)
const orderDetailTitle = ref(null)
const orderDetailTable = ref([])
const queryParams = ref({
  pageSize: 10,
  pageNum: 1,
  sealProduct: '',
})
const resetAddOrderDetail = () => {
  proxy.addOrderDetail = {
    deptId: '',
    totalPower: '',
    orderDeterminedPower: '',
    time: '',
    totalAmount: '',
  }
}
const handleAddOrderDetail = () => {
  if (!proxy.continueOpen) return ElMessage.error('预定日期已截止')
  resetAddOrderDetail()
  openAddOrderDetail.value = true
  addOrderDetailTitle.value = '新增'
}
const editAddOrderDetail = (row: { [key: string]: any }) => {
  if (!proxy.continueOpen) return ElMessage.error('预定日期已截止')
  resetAddOrderDetail()
  openAddOrderDetail.value = true
  addOrderDetailTitle.value = '修改'
  addOrderDetail.value = JSON.parse(JSON.stringify(row))
}
const delAddOrderDetail = (row: { [key: string]: any }) => {
  const { manageId, id } = row
  const data = { manageId, id }
  ElMessageBox.confirm('是否删除？', '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning',
  }).then(() => {
    delOrderDetail(data).then(res => {
      if (res.cede == 200) {
        ElMessage.success('删除成功')
        handleCanbinDetail(row)
      }
    }).catch(err => {
      console.log(err)
    })
  })
}

const submitForm = () => {
  $validateForm(dialogForms.value, () => {
    if (title.value == '新增') {
      insertSysResevePositionManage(dialogForm.value).then(res => {
        if (res.code == 200) {
          ElMessage.success('新增成功')
          cancel()
          mainRef.value.getList()
        } else {
          ElMessage.error(res.msg)
        }
      })
    } else {
      updateSysResevePositionManage(dialogForm.value).then(res => {
        if (res.code == 200) {
          ElMessage.success('修改成功')
          cancel()
          mainRef.value.getList()
        } else {
          ElMessage.error(res.msg)
        }
      })
    }
  })
}

const cancel = () => {
  open.value = false
  reset()
}
const reset = () => {
  proxy.dialogForm = {
    deptId: '',
    sealProduct: '',
    totalPower: '',
    orderDeterminedPower: '',
    time: '',
    totalAmount: '',
  }
  const form = unref(dialogForms)
  form.resetFields()
}
const submitAddOrderDetail = () => {
  addOrderDetail.value.manageId = manageIds.value
 
  $validateForm(addOrderDetails.value, () => {
    if (addOrderDetailTitle.value == '新增') {
      saveManageDeails(addOrderDetail.value).then(res => {
        if (res.code == 200) {
          ElMessage.success('新增成功')
          openAddOrderDetail.value = false
          getList()
          proxy.addOrderDetail = {}
          mainRef.value.getList()
        } else {
          ElMessage.error(res.msg)
        }
      })
    } else {
      updateManageDeails(addOrderDetail.value).then(res => {
        if (res.code == 200) {
          ElMessage.success('修改成功')
          openAddOrderDetail.value = false
          getList()
          proxy.addOrderDetail = {}
          mainRef.value.getList()
        } else {
          ElMessage.error(res.msg)
        }
      })
    }
  })
}
const getList = () => {
  const data = {
    manageId: manageIds.value,
  }
  resevePositionManageDeailsList(data).then(res => {
    if (res.code == 200) {
      orderDetailTable.value = res.data
      xqloading.value = false
    } else {
      xqloading.value = false
    }
  }).catch(() => {
    xqloading.value = false
  })
}
const cancelAddOrderDetail = () => {
  openAddOrderDetail.value = false
  proxy.$refs.addOrderDetails.resetFields()
}

const handleDetail = (row: { [key: string]: any }) => {
  const id = (row.customerCode && row.mid) || row.id
  mids.value = id
  orderDetailForm.value.mid = id
  openDetail.value = true
  titleDetail.value = '预定详情'
  tb3Loading.value = true
  getDetail(orderDetailForm.value).then(res => {
    if (res.code == 200) {
      tb3Loading.value = false
      detailTable.value = res.data
    } else {
      ElMessage.error(res.msg)
      tb3Loading.value = false
    }
  }).catch(() => {
    tb3Loading.value = false
  })
}
const resetOrderDetail = (row) => {
  proxy.orderDetailForm = {}
  handleDetail(row)
}
const cancle2 = () => {
  proxy.orderDetailForm = {}
  openDetail.value = false
}
const handleExport = () => {}
// 预定详情
const forms = ref(undefined)
const mid4 = ref(null)
const customerCode4 = ref(null)
const deptId4 = ref(null)
const form4 = ref({
  status: '',
  mid: mid4,
  customerCode: customerCode4,
  deptId: deptId4,
})

const handleDelDetail = (row: { [key: string]: any }) => {
  open4.value = true
  title4.value = '预定详情'
  loading4.value = true
  form4.value.mid = row.mid
  form4.value.customerCode = row.customerCode
  form4.value.deptId = row.deptId
  mid4.value = row.mid
  customerCode4.value = row.customerCode
  deptId4.value = row.deptId
  getDetail4(form4.value).then(res => {
    loading4.value = false
    if (res.code == 200) {
      data4.value = res.data
    }
  }).catch(() => {
    loading4.value = false
  })
}
const cancle4 = () => {
  open4.value = false
  proxy.form4 = {}
}
const handleDelDetails = (row: { [key: string]: any }) => {
  ElMessageBox.confirm('是否删除？', '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning',
  }).then(() => {
    deleteCustomerBookingSpace({ mid: row.mid, customerCode: row.customerCode, deptId: row.deptId }).then(res => {
      if (res.code == 200) {
        ElMessage.success('删除成功')
        handleDetail(row)
        mainRef.value.getList()
      } else {
        ElMessage.error(res.msg)
      }
    }).catch(err => {
      console.log(err)
    })
  })
}

const handleCabin = () => {
  open.value = true
  title.value = '新增'
}
const handleExportOrderDetail = () => {
  const mids = idss.value
  $download('order/SysOrderWarehouseManagementController/export', { mids }, `预定详情_\
   ${ new Date().getTime() }.xlsx`)
}
const handleEdit = (row: { [key: string]: any }) => {
  open.value = true
  dialogForm.value = JSON.parse(JSON.stringify(row))
  title.value = '修改'
}
// 拦截
const handleValidator = (row: { [key: string]: any }) => {
  const { scheduledStartTime, scheduledEndTime } = row
  const today = new Date()
  if (today > new Date(scheduledEndTime)) {
    continueOpen.value = false
  } else {
    continueOpen.value = true
  }
} 
const manageIds = ref(null)
const handleCanbinDetail = (row: { [key: string]: any }) => {
  const id = row.id
  manageIds.value = row.id
  handleValidator(row)
  xqloading.value = true
  orderDetailTitle.value = '订舱详情'
  orderDetail.value = true
  const data = {
    manageId: id,
  }
  resevePositionManageDeailsList(data).then(res => {
    if (res.code == 200) {
      orderDetailTable.value = res.data
      xqloading.value = false
    } else {
      xqloading.value = false
    }
  }).catch(() => {
    xqloading.value = false
  })
}
const handleDel = (row: { [key: string]: any }) => {
  const id = row.id
  ElMessageBox.confirm('是否删除？', '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning',
  }).then(() => {
    deletePositionManageById(id).then(res => {
      if (res.code == 200) {
        ElMessage.success('删除成功')
        mainRef.value.getList()
      } else {
        ElMessage.error(res.msg)
      }
    })
  })
}
// 订舱详情-详情
const data4 = ref([])
const loading4 = ref(false)
const multiple2 = ref(true)
const ids4 = ref([])
const handleCancelCabin = (row: { [key: string]: any }) => {
  let ids = []
  if (row?.id) {
    ids.push(row.id)
  } else {
    ids = ids4.value
  }
  ElMessageBox.confirm('敏感操作, 是否继续?', '警告', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning',
  }).then(() => {
    cancelReserve({ idList: ids }).then(res => {
      if (res.code == 200) {
        ElMessage.success(res.msg)
        handleDelDetail(row)
      } else {
        ElMessage.error(res.msg)
      }
    })
  })
}
const handdel4 = (row: { [key: string]: any }) => {
  const id = row.id
  ElMessageBox.confirm('是否删除？', '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning',
  }).then(() => {
    deleteDetails(id).then(res => {
      if (res.code == 200) {
        ElMessage.success('删除成功')
        handleDelDetail(row)
        mainRef.value.getList()
      } else {
        ElMessage.error(res.msg)
      }
    })
  })
}

const handleSelect4 = (rows: { [key: string]: any }[]) => {
  ids4.value = rows && rows.map(el => el.id)
  multiple2.value = !rows.length
  isCancelCabin.value = !!rows.find(el => el.statusStr == '预订失败' || el.statusStr == '取消预定' || el.statusStr == '预定失败' || el.statusStr == '取消预订')
}
const idss = ref([])
const handleTableSelect = (rows: { [key: string]: any }[]) => {
  multiple.value = !rows.length
  idss.value = rows.map(el => el.id)
}
const config = computed({
  get() {
    return {
      query: {
        fields: [
		
          {
            type: 'select',
            label: '销售产品',
            prop: 'sealProduct',
            option: {
              dictInfo: { dict: DictDirection.产品 },
            },
          },
      
        ],
        queryParams: queryParams.value,
        formOption: {},
      },
      btns: [
        {
          title: '新增',
          type: 'primary',
          icon: Plus,
          onClick: handleCabin,
        },

        {
          title: '导出预定详情',
          type: 'warning',
          icon: Download,
          disabled: multiple.value,
          onClick: handleExportOrderDetail,
        },
      ],
      table: {
        columns: [
          { type: 'selection', width: '55', align: 'center' },
          { label: '销售产品',
            width: '155',
            align: 'center',
            prop: 'sealProduct',
            autoFormatter: {
              dict: DictDirection.产品,
              rowKey: 'sealProduct',
            } },
          { label: '总方数', align: 'center', prop: 'totalPower' },
          { label: '可订方数', align: 'center', prop: 'orderDeterminedPower' },
          { label: '已定方数', align: 'center', prop: 'determinedPower' },
          { label: '预定开始日期', align: 'center', prop: 'scheduledStartTime' },
          { label: '预定截止日期', align: 'center', prop: 'scheduledEndTime' },
          { label: '开船日', align: 'center', width: '150', prop: 'receivingTime' },
          {
            label: '操作',
            width: '300px',
            fixed: 'right',
            align: 'center',
            render(h, params) {
              const buttons = [
                {
                  title: '修改',
                  clickFun: handleEdit,
                },
                {
                  title: '订舱详情',
                  clickFun: handleCanbinDetail,
                },
                {
                  title: '预定详情',
                  clickFun: handleDetail,
                },
                {
                  title: '删除',
                  clickFun: handleDel,
                }]
              return buttons.map((el) => h(
                ElButton,
                {
                  text: true,
                  type: 'primary',
                  onClick: () => {
                    el.clickFun(params.row)
                  },
                },
                {
                  default: () => el.title,
                },
              ))
            },
          },
        ],
        event: {
          onSelectionChange: (rows) => {
            handleTableSelect(rows)
          },
        },
      },
      api: resevePositionManageList,
      customKey: 'express/mainBusiness/positionManage/predeterminedPositions',
    }
  },
  set(val) {
    return val
  },
})
</script>
<style lang="less" scoped>
/deep/.is-guttered {
  padding: 5px;
}

</style>
